import java.util.Random;

public class MagicBox <T> {
    private final int countMax;
    private final T[] items;

    public MagicBox(int countMax) {
        this.countMax = countMax;
        this.items = (T[]) new Object[countMax];
    }

    public boolean add(T item) {
        for (int i = 0; i < countMax; i++) {
            if (items[i] == null) {
                items[i] = item;
                return true;
            }
        }
        return false;
    }

    public T pick() {
        for (int i = 0; i < countMax; i++) {
            if (items[i] == null) {
                throw new RuntimeException("Коробка не пуста. Свободно ячеек: " + (countMax - i));
            }
        }
        Random random = new Random();
        return items[random.nextInt(countMax)];
    }

}
